package com.leisai.manager.common.utils;

import com.leisai.manager.pojo.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: jim
 * @Date: 2021/12/17/9:44
 * @Description: Tree工具
 */
public class TreeUtil {
    /**
     * 构建json数组
     * @param treeNodes  需要构建的list
     * @param pid  父节点id
     * @return
     */
    public static List<TreeNode> build(List<TreeNode> treeNodes ,Integer pid){
        ArrayList<TreeNode> list = new ArrayList<>();
        for (TreeNode treeNode:treeNodes ) {
            if (treeNode.getPid().equals(pid) ){
                list.add(treeNode);
                innerBuild(treeNodes,treeNode);
            }
        }
        return list;
    }

    /**
     * 构建json对象
     * @param treeNodes 需要构建的list
     * @param pid  父节点id
     * @return
     */
    public static TreeNode build1(List<TreeNode> treeNodes ,Integer pid){
       TreeNode tree = new TreeNode();
        for (TreeNode treeNode:treeNodes ) {
            //最上层的节点
            if (treeNode.getId().equals(pid)){
                tree.setId(pid);
                tree.setName(treeNode.getName());
            }
            if (treeNode.getPid().equals(pid)){
                innerBuild(treeNodes,tree);
            }
        }
        return tree;
    }

    /**
     * 递归添加子节点
     * @param treeNodes
     * @param parentTreeNode
     */
    private static  void innerBuild(List<TreeNode> treeNodes,TreeNode parentTreeNode){
        for (TreeNode treeNode:treeNodes ) {
            if (treeNode.getPid().equals(parentTreeNode.getId()) ){
                List<TreeNode> children = parentTreeNode.getChildren();
                if ( !children.contains(treeNode)){
                    children.add(treeNode);
                    innerBuild(treeNodes,treeNode);
                }
            }
        }
    }

    /**
     * 计算每个节点的value
     * @param tree  这个tree是未经过build构建的list
     * @param item  赋值的节点
     */
    public static void calculate(List<TreeNode> tree, TreeNode item) {
        for (TreeNode node:tree) {
            if (node.getId().equals(item.getId())){
                node.setValue(item.getValue());
                sumNum(tree,item,item.getValue());
            }
        }
    }

    /**
     *
     * @param tree 这个tree是未经过build构建的list
     * @param item 赋值的节点
     * @param num  值
     */
    private static void sumNum(List<TreeNode> tree, TreeNode item,Double num) {
        for (TreeNode node:tree) {
            if (item.getPid().equals(node.getId())){
                Double value = node.getValue();
                if (value == null){
                    value = 0d;
                }
                node.setValue(value+num);
                sumNum(tree,node,num);
            }
        }
    }
}
